package com.ywu.common.mapper;

import org.modelmapper.AbstractConverter;
import org.modelmapper.Converter;
import org.modelmapper.ModelMapper;
import org.modelmapper.convention.MatchingStrategies;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @ClassName YwuBeanMapper
 * @Description TODO
 * @Author GroundDemo
 * @Date 2024/4/14 12:23
 * @Version 1.0
 **/
public class YwuBeanMapper{
    private static final ModelMapper MODEL_MAPPER = new ModelMapper();

    static {

        Converter<String, Date> toStringDate = new AbstractConverter<String, Date>() {
            @Override
            protected Date convert(String source) {
                SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                try {
                    return simpleDateFormat.parse(source);
                } catch (ParseException e) {
                    e.printStackTrace();
                }
                return null;
            }
        };
        MODEL_MAPPER.addConverter(toStringDate);
        MODEL_MAPPER.getConfiguration().setMatchingStrategy(MatchingStrategies.STRICT);
    }

    /**
     * 单个对象拷贝
     */
    public static <D> D map(Object source, Class<D> destinationType) {
        return source == null ? null : MODEL_MAPPER.map(source, destinationType);
    }

    /**
     * 数组对象拷贝
     */
    @SuppressWarnings(value = "unchecked")
    public static <D> List<D> mapList(Object source, Class<D> componentType) {
        if (source == null) {
            return null;
        } else {
            List<D> list = new ArrayList<>();
            List<Object> objectList = (List<Object>) source;
            for (Object obj : objectList) {
                list.add(MODEL_MAPPER.map(obj, componentType));
            }
            return list;
        }
    }

}
